package com.dai.zhenfujin.visitingcard.app;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.dai.zhenfujin.R;
import com.dai.zhenfujin.base.BaseActivity;
import com.dai.zhenfujin.utils.GeoCoderUtil;
import com.dai.zhenfujin.utils.PoiSearchTask;
import com.dai.zhenfujin.visitingcard.adapter.PoiAdapter;
import com.dai.zhenfujin.visitingcard.app.bean.LatLngEntity;
import com.dai.zhenfujin.visitingcard.app.bean.LocationBean;
import com.dai.zhenfujin.visitingcard.app.bean.LocationInfo;

import java.util.ArrayList;
import java.util.List;


/**
 * 名片上面的定位页面
 */
public class LocationActiviy extends BaseActivity implements AMap.OnCameraChangeListener, AdapterView.OnItemClickListener, View.OnClickListener {
    private TextView tvTitle, tvConfirm;
    private FrameLayout imageView;
    private TextView tvSearch;
    private ImageView location_din;
    private MapView mapView;
    private AMap aMap;//地图控制器对象
    private MarkerOptions mMarkerOptions;
    private List<LocationInfo> mList = new ArrayList<LocationInfo>();

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    private AMapLocationClientOption mLocationOption = null;
    //    //声明定位回调监听器
//    public AMapLocationListener mLocationListener = new AMapLocationListener();
    private ListView listView;

    private PoiAdapter adapter;
    private Marker mCenterMarker;
    private LatLonPoint mCurrentPoint;
    private GeocodeSearch mGeocoderSearch;
    private ObjectAnimator mTransAnimator;//地图中心标志动态
    private float zoom = 17;//地图缩放级别
    private String mCity;
    private LocationBean bean;
    private LatLngEntity latLngEntity;
    private String address,title2;
    private int type;
    private double latitude;
    private double longitude;
    private boolean flag = false;
    private ImageView iv_check;
    public ImageView tv_prv_select;
    private boolean isCheck;
    public static String title;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location_activiy);
        type = getIntent().getIntExtra("type", 0);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图 //此方法必须重写
        initView();
        mapView.onCreate(savedInstanceState);
        title = "";

        //初始化地图控制器对象
        if (mapView != null) {
            aMap = mapView.getMap();
            // 自定义系统定位小蓝点
            MyLocationStyle myLocationStyle = new MyLocationStyle();
            myLocationStyle.strokeColor(0x7F0070D9);// 设置圆形的边框颜色
            myLocationStyle.radiusFillColor(0x130070D9);// 设置圆形的填充颜色
            myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
            myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位一次，且将视角移动到地图中心点
            aMap.setMyLocationStyle(myLocationStyle);
            //  //设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            aMap.setMyLocationEnabled(true);
            // 设置地图的缩放级别取值范围[3-20]值越大，显示的越详细
            aMap.getUiSettings().setZoomControlsEnabled(false);
            aMap.moveCamera(CameraUpdateFactory.zoomTo(17.5f));

        }

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());

        //设置定位回调监听
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        mLocationOption.setOnceLocation(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
        //手动移动地图监听 （2）
        aMap.setOnCameraChangeListener(this);

        if (type == 2) {
            double longtitude = getIntent().getDoubleExtra("longitude", 0);
            double latitude = getIntent().getDoubleExtra("latitude", 0);
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longtitude), 17));
        }

        mLocationClient.setLocationListener(aMapLocation -> {
            Log.e("myMap", aMapLocation.getCity());
            Log.e("myMap", aMapLocation.getDistrict());
            Log.e("myMap", aMapLocation.getAddress());

            Log.e("myMap", aMapLocation.toString());
            Log.e("myMap", "查询开始 地址");
            mCity = aMapLocation.getCity();
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    flag = true;
                    //定位成功回调信息，设置相关消息
                    aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    //获取纬度
                    latitude = aMapLocation.getLatitude();
                    //获取经度
                    longitude = aMapLocation.getLongitude();
                    aMapLocation.getAccuracy();//获取精度信息
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 17));

                    PoiSearchTask.getInstance(LocationActiviy.this).setAdapter(adapter).onSearch("", "", latitude, longitude);

                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        });
    }

    private void initListener() {
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        location_din.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(String.valueOf(latitude)))
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 17));
            }
        });


        tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LocationActiviy.this, LocationSearchActivity.class);
                intent.putExtra("city", mCity);
                intent.putExtra("latitude", latitude);
                intent.putExtra("longitude", longitude);
                startActivityForResult(intent, 0);
            }
        });
    }

    private void initView() {

        tvTitle = (TextView) findViewById(R.id.title_textview);
        tvTitle.setText("定位");
        tvConfirm = (TextView) findViewById(R.id.title_tv);
        tvConfirm.setVisibility(View.VISIBLE);
        if (type == 1) {
            tvConfirm.setText("发送");
        } else {
            tvConfirm.setText("确定");
        }
        tvConfirm.setTextColor(getResources().getColor(R.color.yellow));
        imageView = findViewById(R.id.fl_img);
        mapView = (MapView) findViewById(R.id.location_mapview);

        listView = (ListView) findViewById(R.id.listview);

        tvSearch = (TextView) findViewById(R.id.location_search);
        location_din =  findViewById(R.id.location_din);

        adapter = new PoiAdapter(LocationActiviy.this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        tvConfirm.setOnClickListener(this);
      //  location_din.setOnClickListener(this);
        initListener();
    }

    @Override
    protected void onStop() {
        super.onStop();
          mLocationClient.stopLocation();//停止定位*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        flag = false;
    }

    //----------------逆地址编码回调：坐标->地址
    @Override
    public void onCameraChangeFinish(final CameraPosition cameraPosition) {
        latLngEntity = new LatLngEntity(cameraPosition.target.latitude, cameraPosition.target.longitude);
        aMap.clear();
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(cameraPosition.target.latitude, cameraPosition.target.longitude), 17));
        setMarker(cameraPosition);
        //地理反编码工具类
        GeoCoderUtil.getInstance(LocationActiviy.this).geoAddress(latLngEntity, result -> {
            //地图的中心点位置改变后都开始poi的附近搜索
            address = result;
           // if (!TextUtils.isEmpty(address) && address.contains(title)) return;
           // if (!TextUtils.isEmpty(title)) return;
            PoiSearchTask.getInstance(LocationActiviy.this).setAdapter(adapter).onSearch("", "", cameraPosition.target.latitude, cameraPosition.target.longitude);
        });
    }

    private void setMarker(CameraPosition cameraPosition) {
        //绘制marker
        aMap.addMarker(new MarkerOptions()
                .position(new LatLng(cameraPosition.target.latitude, cameraPosition.target.longitude))
                .draggable(true));
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == 1) {
            LocationBean item = (LocationBean) data.getSerializableExtra("item");
            if (null != item) {
                moveCenter(new LatLng(item.getLat(), item.getLon()));
            }
        }
    }


    private void moveCenter(LatLng latLng) {
        if (null != aMap) {
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        isCheck = true;
        bean = (LocationBean) adapter.getItem(position);
        Intent intent = new Intent();
        //  intent.putExtra(EXTRA_DATA, bean);
        //  finish();
        setResult(RESULT_OK, intent);
        title = bean.getTitle();
        title2 = bean.getContent();
       // title2 = title;
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(bean.getLat(), bean.getLon()), 17));

        iv_check = (ImageView) view.findViewById(R.id.iv_check);
        if (tv_prv_select == iv_check) {
            iv_check.setVisibility(View.INVISIBLE);
            tv_prv_select = null;
            return;
        }

        iv_check.setVisibility(View.VISIBLE);
        if (tv_prv_select != null) {
            tv_prv_select.setVisibility(View.INVISIBLE);
        }
        tv_prv_select = iv_check;
    }

    @Override
    public void onClick(View v) {
        Intent intent = this.getIntent();
        intent.putExtra("latitude", latLngEntity.getLatitude());
        intent.putExtra("longitude", latLngEntity.getLongitude());
        if (!TextUtils.isEmpty(address) && address.contains("市")){
            intent.putExtra("address", address.split("市")[0] + "市" + title2);
        }else {
            intent.putExtra("address",  title);
        }

        this.setResult(RESULT_OK, intent);
        finish();
    }
}
